/** SP渠道供应商 */
import {
	Button,
	Collapse,
	Form,
	Row,
	Col,
	Input,
	Select,
	DatePicker,
	Upload,
	InputNumber,
} from 'antd'
import moment from 'moment'
import {PlusCircleOutlined, MinusCircleOutlined} from '@ant-design/icons'
import React, {
	forwardRef,
	useImperativeHandle,
	useEffect,
	useState,
} from 'react'
import type {UploadFile} from 'antd/es/upload/interface'
import {useModel} from 'umi'
import {uploadFileUrl} from '@/service/common/upload'
import styles from './index.less'

const {Panel} = Collapse

type PropsType = {
	type: string | undefined
	dictData: any
	citysList: any
	dataSource: any
	enclosureList: any
	uploadType?: string
}

const channelSupplier = (props: PropsType, ref: any) => {
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const {type, dictData, dataSource, enclosureList} = props
	const [basicsForm] = Form.useForm()
	const [bankForm] = Form.useForm()
	const [contractForm] = Form.useForm()
	const [fileList, setFileList] = useState<UploadFile[]>([])
	// const [subAccountType, setSubAccountType] = useState<number>(2)
	const [startDate, setStartDate] = useState<any>()
	const [endDate, setEndDate] = useState<any>()

	useEffect(() => {
		contractForm.setFieldsValue({
			contractStatus: '根据开始结束时间自动生成',
		})

		if (type !== 'add') {
			const data = dataSource.spInfo
			setStartDate(moment(data?.contractStartDate))
			setEndDate(moment(data?.contractSettlementDate))
			// setSubAccountType(data?.subAccount)
			basicsForm.setFieldsValue({
				...data,
				subAccount:
					data?.subAccount === 0 ? undefined : data?.subAccount,
			})
			const newBankData = dataSource?.bankData
			dataSource?.bankData?.forEach((items: any, index: number) => {
				delete newBankData[index]?.id
			})
			bankForm.setFieldsValue({bankData: newBankData})
			contractForm.setFieldsValue({
				...data,
				contractFileUrl: [],
				contractStartDate: data?.contractStartDate
					? moment(data?.contractStartDate)
					: '',
				contractSettlementDate: data?.contractSettlementDate
					? moment(data?.contractSettlementDate)
					: '',
			})
		} else {
			basicsForm.setFieldsValue({
				...dataSource,
				channelType: '2',
			})
			// 初始一条银行信息
			bankForm.setFieldsValue({
				bankData: [
					{
						bankAccount: undefined,
						accountOpenBank: undefined,
						accountOpenBankName: undefined,
						accountName: undefined,
						bankNo: undefined,
					},
				],
			})
		}
	}, [type, dataSource])

	useEffect(() => {
		if (type !== 'add' && enclosureList?.length) {
			const contractFileUrl = enclosureList?.map(
				(item: {
					id: {toString: () => any}
					filename: any
					url: any
				}) => ({
					uid: item?.id?.toString(),
					name: item?.filename,
					url: item?.url,
				}),
			)
			contractForm.setFieldsValue({
				contractFileUrl,
			})
			setFileList(contractFileUrl)
		}
	}, [type, enclosureList])

	useEffect(() => {
		if (startDate && endDate) {
			const newDate = new Date()
			if (newDate >= startDate && newDate <= endDate) {
				contractForm.setFieldsValue({
					contractStatus: '2',
				})
			} else if (newDate < startDate) {
				contractForm.setFieldsValue({
					contractStatus: '1',
				})
			} else if (newDate > endDate) {
				contractForm.setFieldsValue({
					contractStatus: '3',
				})
			}
		}
	}, [startDate, endDate])

	const customizeHeader = (value: string) => (
		<div>
			<div className={styles.tip} />
			{value}
		</div>
	)
	const onSubmit = async () => {
		const contractFileUrl = fileList?.map(
			(item) => item?.response?.data?.id || item?.uid,
		)
		const basicsValue = await basicsForm.validateFields()
		const bankValue = await bankForm.validateFields()
		const contractValue = await contractForm.validateFields()
		if (basicsValue && bankValue && contractValue) {
			return {
				...basicsValue,
				...bankValue,
				...contractValue,
				agencyService: basicsValue?.agencyService || '',
				cooperationMode: basicsValue?.cooperationMode || '',
				provinceId: basicsValue?.city?.[0],
				cityId: basicsValue?.city?.[1],
				contractStartDate: moment(
					contractValue?.contractStartDate,
				).format('YYYY-MM-DD'),
				contractSettlementDate: moment(
					contractValue?.contractSettlementDate,
				).format('YYYY-MM-DD'),
				contractFileUrl: contractFileUrl?.toString(),
			}
		}
		return {}
	}
	useImperativeHandle(ref, () => ({
		getData: onSubmit,
	}))

	const normFile = (e: any) => {
		if (Array.isArray(e)) {
			return e
		}
		return e?.fileList
	}

	const uploadProps = {
		action: uploadFileUrl,
		name: fileName,
		data: {
			modelName: 'spAccess',
			targetAttr: 13,
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				setFileList(info?.fileList)
			}
			setFileList(info?.fileList)
		},
		fileList,
	}

	return (
		<div className={styles.channelSupplier}>
			<Collapse
				defaultActiveKey={['1', '2', '3']}
				ghost
				expandIconPosition="end"
				collapsible="header">
				<Panel header={customizeHeader('基础信息')} key="1" forceRender>
					<Form
						form={basicsForm}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						disabled={type === 'view' || type === 'process'}>
						<Row gutter={12}>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="企业法人"
									name="legalPerson"
									rules={[{required: true, max: 6}]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="渠道负责人"
									name="channelLeader"
									rules={[{required: true, max: 6}]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="负责人电话"
									name="leadingPhone"
									rules={[
										{required: true},
										{
											pattern:
												/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
											message: '请输入正确的手机号',
										},
									]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="常用地址"
									name="address"
									rules={[{max: 30}]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							{/* <Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="固定电话"
									name="linePhone"
									rules={[
										{
											pattern:
												/^(((\d{3,4})?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/,
											message: '填写的电话格式有误',
										},
									]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col> */}
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="代理业务"
									name="agencyService">
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Agency_Business}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="合作模式"
									name="cooperationMode">
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Cooperation_Mode}
									/>
								</Form.Item>
							</Col>
							{/* <Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="业务模式"
									name="businessModel"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Business_Model}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="公司类型"
									name="companyType"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Company_Type}
									/>
								</Form.Item>
							</Col> */}
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="渠道类型"
									name="channelType"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										disabled
										options={dictData?.Channel_Type}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="渠道标签"
									name="channelLabel"
									rules={[{max: 10}]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="结算周期"
									name="settlementCycle"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Settlement_Cycle}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="税率"
									name="taxRate"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Invoicing_Tax_Rate}
									/>
								</Form.Item>
							</Col>
							{/* <Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="是否有子账户"
									name="subAccount">
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										onSelect={(value: number) =>
											setSubAccountType(value)
										}>
										<Option value={1}>是</Option>
										<Option value={2}>否</Option>
									</Select>
								</Form.Item>
							</Col>
							{subAccountType === 1 ? (
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="开设子账户的条件"
										name="accountConditions">
										<Input
											placeholder={
												type === 'view' ||
												type === 'process'
													? '-'
													: '请输入'
											}
										/>
									</Form.Item>
								</Col>
							) : (
								''
							)} */}
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="结算方式"
									name="settlementMethod"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.SP_Settlement_Method}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="保证金金额"
									name="earnestMoney"
									rules={[
										{required: true},
										{
											pattern:
												/^([0-9]|[1-9]\d+)(\.\d{0,2})?$/,
											message: '小数点后不得超过两位',
										},
									]}>
									<InputNumber
										formatter={(value) => {
											if (
												type === 'view' ||
												type === 'process'
											) {
												return `${value}元`
											}
											return value?.toString() || ''
										}}
										max={1000000000}
										addonAfter="元"
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Panel>
				<Panel header={customizeHeader('银行信息')} key="2" forceRender>
					<Form
						form={bankForm}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						disabled={type === 'view' || type === 'process'}
						autoComplete="off">
						<Form.List name="bankData">
							{(fields, {add, remove}) => (
								<>
									{fields.map((field, index) => (
										<Row gutter={12} key={field.key}>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="银行账号"
													name={[
														field.name,
														'bankAccount',
													]}
													rules={[
														{
															required: true,
															max: 20,
														},
														{
															pattern: /^[0-9]*$/,
															message:
																'银行账号只能输入纯数字',
														},
													]}>
													<Input
														placeholder={
															type === 'view' ||
															type === 'process'
																? '-'
																: '请输入'
														}
													/>
												</Form.Item>
											</Col>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="开户银行"
													name={[
														field.name,
														'bankName',
													]}
													rules={[
														{
															required: true,
															max: 20,
														},
														{
															pattern:
																/^[\u4e00-\u9fa5]{0,}$/,
															message:
																'开户银行只能输入文字',
														},
													]}>
													<Input
														placeholder={
															type === 'view' ||
															type === 'process'
																? '-'
																: '请输入'
														}
													/>
												</Form.Item>
											</Col>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="开户行名称"
													name={[
														field.name,
														'accountBankName',
													]}
													rules={[
														{
															required: true,
															max: 20,
														},
														{
															pattern:
																/^[\u4e00-\u9fa5]{0,}$/,
															message:
																'开户行名称只能输入文字',
														},
													]}>
													<Input
														placeholder={
															type === 'view' ||
															type === 'process'
																? '-'
																: '请输入'
														}
													/>
												</Form.Item>
											</Col>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="开户名称"
													name={[
														field.name,
														'accountName',
													]}
													rules={[
														{
															required: true,
															max: 20,
														},
														{
															pattern:
																/^[\u4e00-\u9fa5]{0,}$/,
															message:
																'开户名称只能输入文字',
														},
													]}>
													<Input
														placeholder={
															type === 'view' ||
															type === 'process'
																? '-'
																: '请输入'
														}
													/>
												</Form.Item>
											</Col>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="联行号"
													name={[
														field.name,
														'bankNo',
													]}
													rules={[
														{
															max: 20,
														},
													]}>
													<Input
														placeholder={
															type === 'view' ||
															type === 'process'
																? '-'
																: '请输入'
														}
													/>
												</Form.Item>
											</Col>
											{index === 0 ||
											type === 'view' ||
											type === 'process' ? (
												''
											) : (
												<Col
													sm={{span: 24}}
													md={{span: 12}}
													lg={{span: 8}}>
													<MinusCircleOutlined
														className={
															styles.remove
														}
														onClick={() =>
															remove(index)
														}
													/>
												</Col>
											)}
										</Row>
									))}
									{fields?.length < 5 &&
									type !== 'view' &&
									type !== 'process' ? (
										<Form.Item>
											<Button
												type="link"
												icon={<PlusCircleOutlined />}
												onClick={() => add()}>
												添加账号信息
											</Button>
										</Form.Item>
									) : (
										''
									)}
								</>
							)}
						</Form.List>
					</Form>
				</Panel>
				<Panel header={customizeHeader('合同信息')} key="3" forceRender>
					<Form
						form={contractForm}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						disabled={type === 'view' || type === 'process'}
						autoComplete="off">
						<Row gutter={12}>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="合同编号"
									name="contractNo"
									rules={[{required: true, max: 50}]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							{/* <Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="合同性质"
									name="contractNature"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Nature_Contract}
									/>
								</Form.Item>
							</Col> */}
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="合同开始日期"
									name="contractStartDate"
									rules={[{required: true}]}>
									<DatePicker
										allowClear={false}
										onChange={(date) => {
											setStartDate(date)
										}}
										disabledDate={(current) =>
											current && current > endDate
										}
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="合同结束日期"
									name="contractSettlementDate"
									rules={[{required: true}]}>
									<DatePicker
										allowClear={false}
										onChange={(date) => {
											setEndDate(date)
										}}
										disabledDate={(current) =>
											current && current < startDate
										}
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="合同状态"
									name="contractStatus"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '根据开始结束时间自动生成'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										disabled
										options={dictData?.Contract_Status}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="我方签约主体"
									name="contractingParties"
									rules={[
										{
											required: true,
											max: 20,
										},
									]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							{/* <Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="联系电话"
									name="telephone"
									rules={[
										{required: true},
										{
											pattern:
												/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
											message: '请输入正确的手机号',
										},
									]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col> */}
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									name="contractFileUrl"
									label="合同上传"
									valuePropName="fileList"
									getValueFromEvent={normFile}
									rules={[
										{required: true, message: '请上传合同'},
									]}
									className={styles.fileUpload}>
									<Upload {...uploadProps}>
										{fileList?.length >= 5 ||
										type === 'view' ||
										type === 'process' ? null : (
											<Button>请选择文件</Button>
										)}
									</Upload>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Panel>
			</Collapse>
		</div>
	)
}

export default forwardRef(channelSupplier)
